package com.google.project.client.Sharing;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.project.client.Director.DRTEntrypoint;
import com.google.project.client.ProjectManager.PMEntrypoint;
import com.google.project.client.Service.LoginService;
import com.google.project.client.Service.LoginServiceAsync;
import com.google.project.client.Service.MessageService;
import com.google.project.client.Service.MessageServiceAsync;
import com.google.project.client.Service.ProjectReportDetailService;
import com.google.project.client.Service.ProjectReportDetailServiceAsync;
import com.google.project.client.Service.ProjectReportService;
import com.google.project.client.Service.ProjectReportServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.UploadService;
import com.google.project.client.Service.UploadServiceAsync;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.DocumentDTO;
import com.google.project.shared.MessageDTO;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectReportDTO;
import com.google.project.shared.ProjectReportDetailDTO;
import com.google.project.shared.UsersDTO;

public class ProjectReportDetail extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField
	Label lblProjectName;
	@UiField
	Label lblSenderName;
	@UiField
	Label lblCreatedOnDate;
	@UiField
	TextArea taReponse;
	@UiField(provided = true)
	CellTable<ProjectReportDetailDTO> cbProjectReportDetail = new CellTable<ProjectReportDetailDTO>();
	@UiField
	SimplePager pager;
	@UiField
	Button btnBack;
	@UiField
	VerticalPanel pWidget;
	@UiField
	Label lblAttach;
	@UiField
	HTMLPanel htmlPanel;
	@UiField Label lblDate;
	@UiField Label lblComplete;

	interface Binder extends UiBinder<Widget, ProjectReportDetail> {
	}

	private final ProjectReportDetailServiceAsync reportDetailSv = GWT
			.create(ProjectReportDetailService.class);
	private final ProjectServiceAsync projectSv = GWT
	.create(ProjectService.class);
	private final ProjectReportServiceAsync projectReportService = GWT
			.create(ProjectReportService.class);
	private final MessageServiceAsync messService = GWT
			.create(MessageService.class);
	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);
	private final UsersServiceAsync userSv = GWT
	.create(UsersService.class);
	private UploadServiceAsync rpc = GWT.create(UploadService.class);

	ProjectReportDTO currentProjectReport = new ProjectReportDTO();
	MessageDTO messDTO = new MessageDTO();
	UsersDTO currentUserDTO = new UsersDTO();
	List<MessageDTO> listMessage = new ArrayList<MessageDTO>();

	public ProjectReportDetail() {
		// initTableForOPT();
		initWidget(binder.createAndBindUi(this));
	}

	// contructor goi vao
	public ProjectReportDetail(ProjectReportDTO projectReport) {
		initTable();
		initWidget(binder.createAndBindUi(this));
		this.currentProjectReport = projectReport;
		getProjectReportDetail(projectReport.getId());	//lấy về báo cáo chi tiết theo projectReportID
		
		lblSenderName.setText(projectReport.getFromUserName());
		lblCreatedOnDate.setText(CommonFuntion.convertToDate(new Date(
				projectReport.getCreatedOnDate())));
		getMessByParentID();
		getUrl(projectReport.getId(), "5"); // get fileUpload -projectReport type=5
		projectSv.getProjectById(projectReport.getProjectId(), new AsyncCallback<ProjectDTO>() {
			
			@Override
			public void onSuccess(ProjectDTO result) {
				lblProjectName.setText(result.getProjectName());
				lblDate.setText("("+CommonFuntion.convertToDate(new Date(result.getStartDate()))+" - "+CommonFuntion.convertToDate(new Date(result.getDueDate()))+")");
				lblComplete.setText(result.getComplete()+" (%)");
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
	
		// get info user from session + lấy thông tin giám đốc with userCode=mg4
		loginService.getCurrentUserDTO(new AsyncCallback<UsersDTO>() {

			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(UsersDTO result) {
				currentUserDTO = result;
				// get name, id cua PM
				userSv.getInfoByUserCode("mg4",
						new AsyncCallback<List<UsersDTO>>() {

							@Override
							public void onFailure(Throwable caught) {
							}

							@Override
							public void onSuccess(List<UsersDTO> result) {
								// pm phan hoi toi dr
								if (currentProjectReport.getFromUserID().equals(
										currentUserDTO.getUserId())) {
									messDTO.setSenderId(currentUserDTO
											.getUserId());
									messDTO.setSenderName(currentUserDTO
											.getUserName());
									messDTO.setReceiverId(result.get(0).getUserId());
									messDTO.setReceiverName(result
											.get(0).getUserName());
								} else { // pm gui lai dr
									messDTO.setSenderId(result.get(0).getUserId());
									messDTO.setSenderName(result
											.get(0).getUserName());
									messDTO.setReceiverId(currentUserDTO
											.getUserId());
									messDTO.setReceiverName(currentUserDTO
											.getUserName());
								}
							}
						});

			}

		});
	}

	// get url link file
	public void getUrl(String forID, String dataType) {
		rpc.getBlobs(forID, dataType, new AsyncCallback<List<DocumentDTO>>() {
			public void onSuccess(List<DocumentDTO> blobData) {
				if (blobData.size() > 0) {
					lblAttach.setVisible(true);
					htmlPanel.setVisible(true);
					String html = "<a target=\"_blank\" href="
							+ blobData.get(0).getUrl() + ">"
							+ blobData.get(0).getDocumentName() + "</a>";
					SafeHtml safeHtml = SafeHtmlUtils.fromSafeConstant(html);
					HTML na = new HTML(safeHtml);
					htmlPanel.add(na);
				}

			}

			public void onFailure(Throwable caught) {
				Window.alert("couldn't get blob list, rpc failed");
			}
		});
	}

	//lấy về báo cáo chi tiết theo projectReportID
	private void getProjectReportDetail(String _projectReportId) {
		reportDetailSv.getProjectReportDetail(_projectReportId,
				new AsyncCallback<List<ProjectReportDetailDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(List<ProjectReportDetailDTO> result) {
						LoadData(result);
					}
				});

	}

	// khởi tạo cho celltable
	public void initTable() {
		// STT
		TextColumn<ProjectReportDetailDTO> index = new TextColumn<ProjectReportDetailDTO>() {
			@Override
			public String getValue(ProjectReportDetailDTO object) {
				return object.getIndex()+"";
			}
		};
		//Tên công việc
		TextColumn<ProjectReportDetailDTO> taskColumn = new TextColumn<ProjectReportDetailDTO>() {
			@Override
			public String getValue(ProjectReportDetailDTO object) {
				return object.getTaskName();
			}
		};
		//Ngày bắt đầu
		TextColumn<ProjectReportDetailDTO> startDate = new TextColumn<ProjectReportDetailDTO>() {
			@Override
			public String getValue(ProjectReportDetailDTO object) {
				return CommonFuntion.convertToDate(new Date(object.getStartDate()));
			}
		};
		//Ngày kết thúc
		TextColumn<ProjectReportDetailDTO> dueDate = new TextColumn<ProjectReportDetailDTO>() {
			@Override
			public String getValue(ProjectReportDetailDTO object) {
				return CommonFuntion.convertToDate(new Date(object.getDueDate()));
			}
		};
		//Khối lượng ban đầu
		TextColumn<ProjectReportDetailDTO> amountOfWork = new TextColumn<ProjectReportDetailDTO>() {
			@Override
			public String getValue(ProjectReportDetailDTO object) {
				return object.getAmountOfWork()+"("+object.getUnit()+")";
			}
		};
		//% hoàn thành
		TextColumn<ProjectReportDetailDTO> percent = new TextColumn<ProjectReportDetailDTO>() {
			@Override
			public String getValue(ProjectReportDetailDTO object) {
				Double finish=object.getFinishWork();
				Double amoutOfWork=object.getAmountOfWork();
				Double rate=(finish/amoutOfWork)*100 ;
				rate =rate*100;
				rate = 0d+rate.intValue();
				rate = rate/100;
				return rate+"(%)";
			}
		};
		cbProjectReportDetail.setStyleName("ttable");
		cbProjectReportDetail.addColumn(index, "STT");
		cbProjectReportDetail.addColumn(taskColumn, "Công việc");
		cbProjectReportDetail
				.addColumn(startDate, "Ngày bắt đầu");
		cbProjectReportDetail.addColumn(dueDate, "Ngày kết thúc");
		cbProjectReportDetail.addColumn(amountOfWork, "Khối lượng");
		cbProjectReportDetail.addColumn(percent, "Hoàn thành(%)");

	}


	// load data fill to celltable
	protected void LoadData(List<ProjectReportDetailDTO> projectReportList) {
		ListDataProvider<ProjectReportDetailDTO> dataProvider = new ListDataProvider<ProjectReportDetailDTO>();
		// Connect the table to the data provider.
		dataProvider.addDataDisplay(cbProjectReportDetail);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		int index = 1;
		List<ProjectReportDetailDTO> list = dataProvider.getList();
		for (ProjectReportDetailDTO projectDetail : projectReportList) {
			projectDetail.setIndex(index);
			list.add(projectDetail);
			index++;
		}
		// SimplePager
		pager.setDisplay(cbProjectReportDetail);
		pager.setPageSize(4);
	}

	// get all Message by ParentID= id của báo cáo cha
	public void getMessByParentID() {
		messService.getMessageList(new AsyncCallback<List<MessageDTO>>() {

			@Override
			public void onSuccess(List<MessageDTO> result) {
				try {
					for (MessageDTO messageDTO : result) {
						listMessage.add(messageDTO);
					}

					List<MessageDTO> tempMess = new ArrayList<MessageDTO>();
					for (MessageDTO mess : listMessage) {
						if (mess.getParentId()!=null && mess.getParentId().equals(
								currentProjectReport.getId())) {
							tempMess.add(mess);
						}
					}
					String top = "<div class=\"container3\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					String top2 = "<div class=\"container2\"><div class=\"smallpbox\"><div class=\"smallpboxtl\"></div><div class=\"smallpboxtr\"></div></div><div class=\"smallpboxcnt\">";
					String bottom2 = "</div><div class=\"smallpboxbtm\"><div class=\"smallpboxbtml\"></div><div class=\"smallpboxbtmr\"></div></div></div>";
					if (tempMess != null && tempMess.size() > 0) {
						int r = tempMess.size();
						int c = 1;
						Grid grid = new Grid(r, c);
						pWidget.add(grid);
						for (int i = 0; i < tempMess.size(); i++) {
							String senderName = tempMess.get(i).getSenderName();
							String content = tempMess.get(i).getContent();
							String createdOnDate = CommonFuntion
									.convertToDate(new Date(tempMess.get(i)
											.getCreatedOnDate()));
							grid.setWidget(i, 0, new HTML(top + "Người Gửi: "
									+ senderName + " <br> Ngày Gửi: "
									+ createdOnDate + "<br><br>" + top2
									+ content + bottom2 + bottom + "<br>"));
						}

					}

					Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
				        public void execute () {
				        	taReponse.setFocus(true);
				        }
				    });

				} catch (Exception ex) {
					ex.getMessage();
				}
			}

			@Override
			public void onFailure(Throwable caught) {
			}
		});
	}

	// gui phan hoi
	@UiHandler("btnReponse")
	void onBtnReponseClick(ClickEvent event) {
		messDTO.setContent(taReponse.getText());
		messDTO.setCreatedOnDate(new Date().getTime());
		messDTO.setParentId(currentProjectReport.getId());
		messDTO.setProjectId(currentProjectReport.getProjectId());
		messDTO.setTypeId(2);
		messService.sendMessage(messDTO, new AsyncCallback<MessageDTO>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(MessageDTO result) {
				// set lai status cua report cha
				if (currentProjectReport.getFromUserID().equals(
						currentUserDTO.getUserId())) {
					projectReportService.updateStatusProjectReport(
							currentProjectReport.getId(), 1,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									Window.alert("Hệ thống hiện tại không thể thực hiện yêu cầu này!");
								}

								@Override
								public void onSuccess(Void result) {
									if(listMessage.size()>0){
										pWidget.clear();
										listMessage.clear();
										}
									getMessByParentID();
									taReponse.setText("");
									Window.alert("Gửi phản hồi thành công!");
								}
							});
				} else {
					projectReportService.updateStatusProjectReport(
							currentProjectReport.getId(), 2,
							new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									Window.alert("Hệ thống hiện tại không thể thực hiện yêu cầu này!");
								}

								@Override
								public void onSuccess(Void result) {
									if(listMessage.size()>0){
										pWidget.clear();
										listMessage.clear();
										}
									getMessByParentID();
									taReponse.setText("");
									Window.alert("Gửi phản hồi thành công!");
								}
							});
				}

			}
		});
	}

	@UiHandler("btnBack")
	void onBtnBack2Click(ClickEvent event) {
		if (currentUserDTO.getUserGroup() == 1) {
			DRTEntrypoint.get().DRTProjectReportList();
		}
		if (currentUserDTO.getUserGroup() == 2) {
			PMEntrypoint.get().PMProjectReportList();
		}
	}
}
